import os

import cv2

'''图片处理测试'''


# 返回指定路径图像的拉普拉斯算子边缘模糊程度值
def getImageVar(img_path):
    image = cv2.imread(img_path)
    img2gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    imageVar = cv2.Laplacian(img2gray, cv2.CV_64F).var()
    return imageVar


# 返回给定文件夹下所有图片的路径列表
def listFolderImgPath(folder_img_path):
    img_path_list = []
    for filename in os.listdir(folder_img_path):
        filepath = os.path.join(folder_img_path, filename)
        img_path_list.append(filepath)
    return img_path_list


# 给单张图片添加文字(图片路径，文字)
def writeText(img_path, text):
    # 加载背景图片
    # img的类型是np.ndarray数组
    img = cv2.imread(img_path)
    # 在图片上添加文字信息
    # 颜色参数值可用颜色拾取器获取（(255,255,255)为纯白色）
    # 最后一个参数bottomLeftOrigin如果设置为True，那么添加的文字是上下颠倒的
    composite_img = cv2.putText(img, text, (100, 680), cv2.FONT_HERSHEY_SIMPLEX,
                                2.0, (255, 255, 255), 5, cv2.LINE_AA, False)
    cv2.imwrite(img_path, composite_img)


def del_low_quality_img(folder_img_path, base_image_var):
    for dirpath, dirnames, filenames in os.walk(folder_img_path):
        for filename in filenames:
            if filename.__contains__('.jpg') or filename.__contains__('.png'):
                filepath = os.path.join(dirpath, filename)
                image_var = getImageVar(filepath)
                text_str = 'The fuzzy is: {:.2f}, filepath: {}'.format(image_var, filepath)
                if image_var < base_image_var or image_var>300:  # 算子低于80表明模糊，后续可以修改改值
                    os.remove(filepath)
                    text_str += ",deleted!"
                print(text_str)


if __name__ == '__main__':
    base_image_var = 100
    folder_img_path = r'D:\like\desktop1\202206'
    del_low_quality_img(folder_img_path, base_image_var)
